const {
	WSclose
} = require("./ws");
const addOnlienUser=require('./online/index.js');
// 时间格式化
function getdate(d, typeM) {
	var date = new Date();
	if (d) {
		date = new Date(d);
	}
	var year = date.getFullYear();
	var month = init(date.getMonth() + 1);
	var day = init(date.getDate());
	var H = init(date.getHours());
	var M = init(date.getMinutes());
	var S = init(date.getSeconds());
	var m = init(date.getMilliseconds());
	let res = typeM == 'm' ? `${year}-${month}-${day} ${H}:${M}:${S}:${m}` : `${year}-${month}-${day} ${H}:${M}:${S}`
	return res;
}

function init(n) {
	return n < 10 ? '0' + n : n;
}
// 时间差 newDate oldDate
function timeDifference(newDate, oldDate) {
	let Date1 = new Date(newDate);
	let Date2 = new Date(oldDate);
	let time = Date1.getTime() - Date2.getTime();
	return time >= 0 ? time : -time;
}
/**
 获取在线人的信息type3 status: 1为用户上线 0下线
	用户信息 wid, username, 
	状态备注 remarks update login
*/
function handledOnline(status, wid, username, token, remarks,ip) {
	let send = {
		code: 200,
		message: "用户状态消息",
		type: 3,
		data: wsClientUsers,
		userCount: 0,
		status: status,
		Id: wid,
		username: username,
		onlineTime: getdate()
	}

	if (status) {
		send.userCount = userCount
		if (wsClients[wid].length<=1) {
			WSsendAll(send) //全推
		}else{
			WSsendMessage(send,wid,token)
		}
	} else {
		userCount--;
		send.userCount = userCount
		WSclose(wid, token);
		if (wsClientUsers[wid] == undefined) {
			WSsendAll(send, wid)
		}
		addOnlienUser(wid,"","close",0,ip)
	}
}

module.exports = {
	getdate,
	timeDifference,
	handledOnline
};